package com.tcd.helper.redis;

import com.tcd.utils.AccountUtils;
import com.tcd.utils.JsonUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName : com.tcd.helper.redis.HashRedisHelper
 * @Description : 描述
 * Author : space
 * CreatedDate 2021-05-26 17:24:32
 */
public class HashRedisHelper extends RedisHelper{
    public static void addHash(String hashName, String field, List dataList, Boolean isReplace){
        if (isReplace && redisTemplate.hasKey(hashName)){
            redisTemplate.delete(hashName);
        }
        for (Object data : dataList) {
            redisTemplate.opsForHash().put(hashName, AccountUtils.getFieldVal(data,field), JsonUtils.objectToJson(data));
        }
    }
    public static void addIfAbsentHash(String hashName,String field, List dataList){
        if (!redisTemplate.hasKey(hashName)){
            addHash(hashName,field,dataList,false);
        }
    }
    public static void addHash(String hashName,String field, Object obj){
        redisTemplate.opsForHash().put(hashName,AccountUtils.getFieldVal(obj,field),JsonUtils.objectToJson(obj));
    }
    public static void updateHash(String hashName,String field, Object obj){
        if (!redisTemplate.opsForHash().hasKey(hashName,AccountUtils.getFieldVal(obj,field))){
            System.err.println("修改失败，未找到该数据");
            return;
        }
        addHash(hashName, field, obj);
    }
    public static void deleteHash(String hashName,Integer... scores ){
        redisTemplate.opsForHash().delete(hashName,scores);
    }
    public static List getValHash(String hashName, Class cls, Integer start, Integer count){
        List list = new ArrayList();
        List<Object> datas = redisTemplate.opsForHash().values(hashName);
        for (int i = start; i < datas.size() && (count == 0 || i < start + count); i++) {
            list.add(JsonUtils.jsonToPojo(datas.get(i).toString(),cls));
        }
        return list;
    }
    public static Integer getValCountHash(String hashName){
        return redisTemplate.opsForHash().size(hashName).intValue();
    }
}
